from rest_framework import status
from rest_framework.views import APIView
from utils.centent.cos import credential
from django.db.models import F
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView

from api import models

from api.serializer import auction
from utils.common import config, add
from utils.common import filters, pagination
from utils.common.auth import JWTAuthentication


class AuctionListAPIView(ListAPIView):
    """拍卖场列表视图
    http://127.0.0.1:8090/api/auction/list/
    """
    authentication_classes = [JWTAuthentication]
    # 以热度进行排列
    queryset = models.Auction.objects.filter(status__in=[2, 3, 4], is_delete=False, is_show=True,
                                             is_operation=False).order_by('-hot', '-look_count', 'id')
    serializer_class = auction.AuctionModelSerializer

    def list(self, request, *args, **kwargs):
        """做优化，如果在序列化器里面查询商品封面。需要查很多次"""
        response = super(AuctionListAPIView, self).list(request, *args, **kwargs)
        # 获取所有的拍卖场id
        auction_id_list = [item['id'] for item in response.data]
        # 通过id取出其所对应的拍品
        auction_item_list = models.AuctionItem.objects.filter(auction_id__in=auction_id_list).values('cover',
                                                                                                     'auction')
        # 一级构造
        new_data = response.data
        new_dic = {}
        for item in new_data:
            new_dic[item['id']] = item
            item['children'] = []
        # 二级添加
        for row in auction_item_list:
            if row['auction'] in new_dic:
                new_dic[row['auction']]['children'].append(row['cover'])
        # print(new_dic.values())
        response.data = new_dic.values()
        return response


class AuctionItemListAPIView(RetrieveAPIView):
    """单个拍卖场&&商品列表视图
    http://127.0.0.1:8090/api/auction/item/2/
    """

    authentication_classes = [JWTAuthentication]
    queryset = models.Auction.objects.filter(is_delete=False, is_show=True, status__gt=1)
    serializer_class = auction.AuctionItemModelSerializer

    def retrieve(self, request, *args, **kwargs):
        """添加浏览记录"""
        response = super(AuctionItemListAPIView, self).retrieve(request, *args, **kwargs)
        # 添加观看记录
        # 修改auction观看数量
        # 修改auction热度
        # 判断是否登录,如果登录添加,未登录,不添加记录
        # models.Replace.object.get(pk=pk) # 返回详情视图所需的模型类数据对象
        auction_obj = self.get_object()
        # 热度增加
        add.add_hot(models.Auction, auction_obj.id, config.HOT_COMMENT)
        # print(auction_obj.hot)
        if request.user:
            query_user = models.BrowseRecordAuction.objects.filter(is_show=True, is_delete=False, item=auction_obj,
                                                                   user=request.user)
            # 判断当前动态中是否该用户的访客记录,如果有,不添加
            exist = query_user.exists()
            if not exist:
                models.BrowseRecordAuction.objects.create(item=auction_obj, user=request.user)
                # 访问记录加一
                models.Auction.objects.filter(id=auction_obj.id).update(look_count=F('look_count') + 1)

        # 获取当前的拍卖场，修改返回的数据
        new_data = response.data
        good_list = models.AuctionItem.objects.filter(auction=self.get_object(), is_show=True,
                                                      is_delete=False).values('id', 'title',
                                                                              'cover', 'start_price',
                                                                              'deal_price', 'reserve_price',
                                                                              'highest_price', 'unit',
                                                                              'bid_count', 'look_count')
        new_data['good_list'] = good_list
        response.data = new_data
        return response


class AuctionItemDetailAPIView(RetrieveAPIView):
    """商品详细视图"""
    queryset = models.AuctionItem.objects.filter(is_delete=False, is_show=True, status__gt=1).order_by('-hot',
                                                                                                       '-look_count',
                                                                                                       'id')
    serializer_class = auction.AuctionItemDetailModelSerializer

    def retrieve(self, request, *args, **kwargs):
        """添加浏览记录"""
        response = super().retrieve(request, *args, **kwargs)
        # 添加观看记录
        # 修改auction_item观看数量
        # 修改auction_item热度
        # 判断是否登录,如果登录添加,未登录,不添加记录
        # models.Replace.object.get(pk=pk) # 返回详情视图所需的模型类数据对象
        auction_item_obj = self.get_object()
        # 热度增加
        add.add_hot(models.AuctionItem, auction_item_obj.id, config.HOT_COMMENT)
        # print(auction_item_obj.hot)
        # print(request.user.__dict__)

        if request.user:
            query_user = models.BrowseRecord.objects.filter(is_show=True, is_delete=False, item=auction_item_obj,
                                                            user=request.user)
            # 判断当前动态中是否该用户的访客记录,如果有,不添加
            exist = query_user.exists()
            if not exist:
                models.BrowseRecord.objects.create(item=auction_item_obj, user=request.user)
                # 访问记录加一
                models.AuctionItem.objects.filter(id=auction_item_obj.id).update(look_count=F('look_count') + 1)

        return response
